var express = require('express');
var router = express.Router();
const http = require('http');
let { userModel, roleModel, menuModel, tokenModel, friendModel, groupModel, messagerModel, MessageStatusModel } = require("../model/model")
// 刘子祥
let jwt = require('jsonwebtoken');
const multiparty = require('multiparty');
const ACCESS_TOKEN_EXPIRATION = 5; //访问令牌有效期
const REFRESH_TOKEN_EXPIRATION = '1d'; //刷新令牌有效期
const SECRET_KEY = 'WANGJIALONG';
const refreshTokenMap = new Map();

const socketIo = require("socket.io")
const server = http.createServer(router)

const userSocketMap = {}; // 用来存储用户ID和Socket ID的映射

const io = socketIo(server, {
  cors: {
    origin: 'http://localhost:5173', // 前端地址
    methods: ['GET', 'POST'],
    allowedHeaders: ['Content-Type'],
  }
})

// 当用户连接时
io.on("connection", (socket) => {
  console.log("用户已连接", socket.id)
  // 监听用户登录
  socket.on("login", async (userID) => {
    userSocketMap[userID] = socket.id   // 将用户ID和socket的映射关系存入全局变量中
    console.log(`用户 ${userID} 已注册,Socket ID:${socket.id}`);
    // 获取未处理的好友请求(状态为0,待处理)
    const pendingRequests = await friendModel.find({
      friendID: userID,
      status: 0
    }).populate("userID", "username")
    // 如果有未处理的请求，发送给客户端
    if (pendingRequests.length > 0) {
      socket.emit("pendingFriendRequests", pendingRequests)
    }
  })
  // 监听消息的发送
  socket.on("send-message", (messageData) => {
    const newMessage = new messagerModel(messageData)
    newMessage.save().then(() => {
      // 广播消息给所有成员
      io.to(messageData.receiver_id).emit("receive-message", newMessage);   // 广播消息给接收者
      io.to(messageData.group_id).emit("receive-message", newMessage)   // 广播消息给群组成员
    })
  })
  // 加入特定的房间(如群聊)
  socket.on("join-room", (roomId) => {
    socket.join(roomId)
  })
  // 断开连接
  socket.on("disconnect", () => {
    // 找到对应的 userID 并删除映射
    for (let userID in userSocketMap) {
      if (userSocketMap[userID] === socket.id) {
        delete userSocketMap[userID];
        console.log(`用户 ${userID} 已断开连接`);
        break;
      }
    }
  })
})

server.listen(3666, () => {
  console.log("服务器已启动，监听端口 3666")
})

// 生成函数令牌
function generateToken(name, expiration) {
  return jwt.sign({ name }, SECRET_KEY, { expiresIn: expiration });
}

// 封装生成短token和长token
function getToken(name) {
  let accessToken = generateToken(name, ACCESS_TOKEN_EXPIRATION); //短Token
  let refreshToken = generateToken(name, REFRESH_TOKEN_EXPIRATION); //长Token
  const refreshTokens = refreshTokenMap.get(name) || [];
  refreshTokens.push(refreshToken);
  refreshTokenMap.set(name, refreshTokens);
  return {
    accessToken,
    refreshToken,
  };
}

//=================================>手机号密码登录
router.post("/login", async (req, res) => {
  let { username, password } = req.body
  let uls = await userModel.findOne({ username })
  if (!uls) {
    return res.status(200).send({ message: "该用户未注册", code: 1 })
  }
  if (uls.password !== password) {
    return res.status(200).send({ message: "密码错误", code: 2 })
  }
  let roleid = await roleModel.find({ _id: uls.roleid })
  let { accessToken, refreshToken } = getToken(uls.username)
  res.send({
    code: 200,
    message: "登录成功",
    roleid: roleid[0].name === '超级管理员' ? 'admin' : 'user',
    username: uls,
    accessToken,
    refreshToken
  })
})

// 刷新短token
router.get('/refresh', async (req, res) => {
  const refreshToken = req.headers.refreshtoken;
  if (!refreshToken) {
    res.status(403).send('Forbidden');
  }
  try {
    const { name } = jwt.verify(refreshToken, SECRET_KEY);
    const accessToken = generateToken(name, ACCESS_TOKEN_EXPIRATION);
    res.status(200).send({ accessToken });
  } catch (error) {
    console.log('长token已过期');
    res.status(403).send('Forbidden');
  }
});


//头像
router.post('/upload', (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = 'upload';
  form.parse(req, function (err, fields, files) {
    res.send({
      code: 200,
      msg: "上传成功",
      img: "http://localhost:3000/" + files.avatar[0].path
    })
  });
})

//用户注册
router.post('/addUser', async (req, res) => {
  let { username, phone } = req.body
  let uls = await userModel.find({ username, phone })
  console.log(uls);

  if (uls.length > 0) {
    res.send({
      code: 202,
      msg: "该手机号或用户名已注册",
    })
  } else {
    let user = await userModel.create(req.body)
    res.send({
      code: 200,
      msg: "注册成功",
      user
    })
  }
})

//修改密码
router.post('/changePassword', async (req, res) => {
  let body = req.body
  let _id = body._id
  await userModel.updateOne({ _id: _id }, { $set: { password: body.password } })
  res.send({
    code: 200,
    msg: "修改成功"
  })
})

//修改个人信息;
router.post('/changeInfo', async (req, res) => {
  let body = req.body
  let _id = body._id
  await userModel.updateOne({ _id: _id }, { $set: { username: body.username, phone: body.phone, imgUrl: body.imgUrl, remark: body.remark } })
  res.send({
    code: 200,
    msg: "修改成功"
  })
})


//获取无限极查询内容
router.get("/getmenulist", async (req, res) => {
  let _id = req.query._id
  let [{ menuid }] = await roleModel.find({ _id })
  let menulist = await menuModel.find({ _id: { $in: menuid } }).lean()
  let json = {}
  menulist.forEach(item => {
    json[item._id] = item
  })
  let data = []
  menulist.forEach(item => {
    if (!item["pid"]) {
      data.push(item)
    } else {
      if (json[item.pid] && !json[item.pid]["children"]) {
        json[item.pid]["children"] = []
      }
      json[item.pid] && json[item.pid]["children"].push(item)
    }
  })
  res.send({
    code: 200,
    msg: "获取成功",
    data
  })
})

// 添加路由
router.post("/addmenu", async (req, res) => {
  await menuModel.create(req.body)
  res.send({
    code: 200,
    msg: "添加成功"
  })
})

// 查找可以添加为好友的用户
router.post("/getOneUser", async (req, res) => {
  const { username, userID } = req.body;  // 获取当前用户名和用户ID
  let result = [];
  if (username) {
    if (username === "全部") {
      result = await userModel.find();
    } else {
      result = await userModel.find({ username: { $regex: new RegExp(username, "i") } });
    }
  }
  if (username === "") {
    return res.send({
      code: 400,
      msg: "请输入查找用户姓名",
    });
  }
  // 模糊查询所有名字带有username的用户

  if (result.length > 0) {
    // 查找每个用户与当前用户之间的好友请求状态，并筛选出可以添加好友的用户
    const updatedResult = await Promise.all(result.map(async (user) => {
      // 如果是当前用户自己，跳过
      if (user._id.toString() === userID.toString()) {
        return null;  // 不返回当前用户自己
      }
      // 查找当前用户与目标用户之间的好友请求记录
      const friendRequest = await friendModel.findOne({
        $or: [
          { userID, friendID: user._id },          //查询当前用户发出的请求（即当前用户 userID 向目标用户 user._id 发送的请求）。
          { userID: user._id, friendID: userID }   //查询目标用户发出的请求（即目标用户 user._id 向当前用户 userID 发送的请求）。
        ]
      });
      // 计算好友请求状态
      let status = 0; // 默认状态 0-待处理
      if (friendRequest) {
        status = friendRequest.status;  // 获取请求状态
      }
      // 只返回可以添加为好友的用户
      if (status === 0 || status === 2) {  // 可以添加好友的条件：待处理或已拒绝
        return { ...user.toObject(), friendshipStatus: status };
      }
      return null;  // 如果已经是好友或者其他状态，不返回该用户
    }));

    // 过滤掉返回结果中的 null 值（即不符合条件的用户）
    const filteredResult = updatedResult.filter(user => user !== null);

    // 返回带有状态信息的用户数据
    return res.send({
      code: 200,
      msg: "查找成功",
      data: filteredResult,
    });
  } else {
    // 没有找到用户
    return res.send({
      code: 202,
      msg: "未找到该用户",
      data: null,
    });
  }
});

// 发起好友请求
router.post("/sendFriend", async (req, res) => {
  const { userID, friendID } = req.body;
  const newRequest = new friendModel({ userID, friendID });
  await newRequest.save();
  // 查找接收好友请求方的socket
  const friendSocketId = userSocketMap[friendID];  // 根据friendID获取socketID
  console.log(friendSocketId, "----------------")
  if (friendSocketId) {
    const friendSocket = io.sockets.sockets.get(friendSocket) //获取接收方的socket对象
    if (friendSocket) {
      // 向接收方发送“有新好友请求”的通知
      friendSocket.emit("newFriendRequest", {
        from: userID,
        to: friendID
      });
    }
  }
  res.send({
    code: 200,
    msg: "请求消息已发送"
  })
})

// 获取离线未处理的好友请求
router.post("/getPendingRequests", async (req, res) => {
  const { userID } = req.body
  const requesets = await friendModel.find({
    friendID: userID,
    status: 0, //只查找待处理的请求
  }).populate("userID", "username")
  res.send({
    code: 200,
    msg: "获取未处理请求成功",
    data: requesets
  })
})

// 同意好友请求
router.post("/acceptFriend", async (req, res) => {
  const { requestId } = req.body;
  const request = await friendModel.findById(requestId);
  if (!request || request.status !== 0) {
    res.send({
      code: "400",
      msg: "请求不存在或已处理"
    })
  }
  request.status = 1;
  await request.save();
  res.send({
    code: "200",
    msg: "好友请求已接收"
  })
})

// 拒绝好友请求
router.post("/rejectFriend", async (req, res) => {
  const { requestId } = req.body;
  const request = await friendModel.findById(requestId);
  if (!request || request.status !== 0) {
    res.send({
      code: "400",
      msg: "请求不存在或已处理"
    })
  }
  request.status = 2;
  await request.save();
  res.send({
    code: "200",
    msg: "好友请求已拒绝"
  })
})

// 获取当前用户的好友列表
router.post("/getFriends", async (req, res) => {
  const { userID } = req.body;
  const friends = await friendModel.find({
    $or: [
      { userID, status: 1 },            //当前用户发起的已接受请求
      { friendID: userID, status: 1 }    //其他用户发起的已接受请求
    ]
  }).populate("userID", "username").populate("friendID", "username");
  const friendList = friends.map(item => {
    return item.userID._id.toString() === userID ? item.friendID : item.userID
  })
  res.send({
    code: 200,
    msg: "获取好友列表成功",
    data: friendList
  })
})

// 获取单个用户详细信息
router.post("/gerUserInfo", async (req, res) => {
  const { userID } = req.body;
  const user = await userModel.findById(userID);
  if (user) {
    res.send({
      code: 200,
      msg: "用户信息获取成功",
      data: user
    })
  } else {
    res.send({
      code: 202,
      msg: "未找到该用户",
      data: null
    })
  }
})

// 更新用户信息
router.post("/updateUserInfo", async (req, res) => {
  const { userID, updateData } = req.body;
  const updateUser = await userModel.findByIdAndUpdate(userID, updateData, { new: true });
  if (updateUser) {
    res.send({
      code: 200,
      msg: "用户信息更新成功",
      data: updateUser
    })
  } else {
    res.send({
      code: 400,
      msg: "更新失败",
    })
  }
})

// 获取群列表
router.post("/getGroups", async (req, res) => {
  const groups = await groupModel.find();
  res.send({
    code: 200,
    msg: "获取群列表成功",
    data: groups
  })
})

// 获取群组成员
router.post("/getGroupMembers", async (req, res) => {
  const { groupID } = req.body;
  const group = await groupModel.findById(groupID).populate("members", "username");
  if (group) {
    res.send({
      code: 200,
      msg: "获取群组成员成功",
      data: group.members
    })
  } else {
    res.send({
      code: 404,
      msg: "未找到该群组",
      data: null
    })
  }
})
//获取角色
router.get('/rolelist', async (req, res) => {
  let data = await roleModel.find()
  res.send({
    code: 200,
    msg: "获取成功",
    data
  })
})


module.exports = router;
